# -*- coding: utf-8 -*-
# @Author: long
# @Date:   2017-12-18 06:20:59
# @Last Modified by:   long
# @Last Modified time: 2017-12-19 05:00:22

import uuid
import time
from socket import *
from HookUtil import ProxyThreadPool

SOCKET_BUFFSIZE = 2048

def wrap_data(xxid, data):
	return "hook-data: %s\n%s"%(xxid, data)

class HookServerHandle(object):
	"""docstring for HookServerHandle"""
	def __init__(self, name, client_socket, client_addr):
		super(HookServerHandle, self).__init__()
		self.name = name
		self.client_socket = client_socket
		self.client_addr = client_addr
		self.source_data_queue = []
		self.source_sockets = {}
		self.on = True

	def client_socket_send(self, data):
		print "==client_socket_send========="
		print data
		print "============================="
		self.client_socket.send(data)

	# 遍历当前数据缓存队列，将队列中的数据发送到client
	def start_send_to_client(self):
		def run():
			while self.on:
				while True:
					data = self.dequeue_soruce_data()
					if not data:
						break
					self.client_socket_send(data)
				time.sleep(1)
		ProxyThreadPool.new_thread(run)

	# 分发client过来的数据，解析后将数据发送到source端
	def dispatch_recv_data(self, data):
		print "=======dispatch_recv_data======="
		if data.startswith("hook-data:"):
			fpos = data.index("\n")
			xxid = data[:fpos].split()[1].strip()
			source_socket = self.get_source_socket_by_xxid(xxid)
			source_socket.send(data[fpos+1:])
			print data
		else:
			print "*****invaild data format****"
			print data
		print "================================"

	# 收取client发送过来的数据
	def start_recv_from_client(self):
		def run():
			while self.on:
				print "^^^^^^^^^^^^^^^"
				data = self.client_socket.recv(SOCKET_BUFFSIZE)
				print "^^^^^^^^^^start_recv_from_client^^^^^^^^^^"
				print data
				print "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
				if not data:
					break
				try:
					self.dispatch_recv_data(data)
				except Exception as e:
					print repr(e)
					# raise e
					raise
		ProxyThreadPool.new_thread(run)					

	def add_connect(self, client_socket, client_addr):

		pass

	def close(self):
		self.on = False

	def dequeue_soruce_data(self):
		data = False
		if len(self.source_data_queue) > 0:
			data = self.source_data_queue[0]
			del self.source_data_queue[0]
		return data

	def append_data(self, xxid, data):
		self.source_data_queue.append(wrap_data(xxid, data))

	def tunnel(self, xxid, source_socket):
		def run_tunnel():
			while self.on:
				data = source_socket.recv[SOCKET_BUFFSIZE]
				if not data:
					break
				self.append_data(xxid, data)
			source_socket.close()
		ProxyThreadPool.new_thread(run_tunnel)

	def get_source_socket_by_xxid(self, xxid):
		print self.source_sockets
		return self.source_sockets[xxid]

	def source_request(self, source_socket, source_addr, header_str):
		# request uri uuid
		print "******xxxx: header_str******\n"
		print header_str
		print "****************************\n"

		xxid = uuid.uuid5(uuid.NAMESPACE_URL, str(source_addr))
		xxid = str(xxid)
		self.source_sockets[xxid] = source_socket
		self.append_data(xxid, header_str)
		while True:
			data = source_socket.recv(SOCKET_BUFFSIZE)
			if not data:
				break
			self.append_data(xxid, data)

